import Router from '@koa/router'
import { map, pick } from 'lodash'
import { insert, like, select, delete as sqlDelete, update } from 'mysql-bricks'
import { query } from '../models'

/**
 * 获取套餐列表
 */
export const getPackagePageController: Router.Middleware = async (ctx) => {
    const picked = pick(ctx.query, ['name'])
    const whereExp = map(picked, (v, k) => like(k, `%${v}%`))
    const page = ctx.query.page || 1
    // 生成sql
    const sql = select()
        .from('package')
        .where(...whereExp)
        .limit(+ctx.query.limit || 10)
        .offset((+page - 1) * 10)
        .toString()
    console.log(sql)
    // 执行sql
    const res = await query(sql)
    const total = await query('select count(*) as total from package')
    // 返回数据
    ctx.body = {
        total: total[0].total,
        rows: res,
    }
}

/**
 * 添加套餐
 */
export const postPackageController: Router.Middleware = async (ctx) => {
    // 获取请求参数
    const data = ctx.request.body
    // 生成sql
    const sql = insert().into('package').values(data).toString()
    // 执行sql
    const res = (await query(sql)) as any
    // 返回数据
    ctx.body = {
        id: res.insertId,
    }
}

/**
 * 修改套餐信息
 */
export const putPackageByIdController: Router.Middleware = async (ctx) => {
    const id = +ctx.params.id!
    const data = ctx.request.body
    // 生成sql
    const sql = update('package', data).where('id', id).toString()
    // 执行sql
    const res = await query(sql)
    // 返回数据
    ctx.body = true
}

/**
 * 删除套餐
 */
export const deletePackageByIdController: Router.Middleware = async (ctx) => {
    const id = +ctx.params.id!
    // 生成sql
    const sql = sqlDelete().from('package').where('id', id).toString()
    // 执行sql
    const res = await query(sql)
    // 返回数据
    ctx.body = true
}
